<template>
  <el-dialog :visible="showRoleDialog" title="分配角色" @close="closeDialog" @open="openRoleDialog">
    <el-checkbox-group v-model="roleIds" v-loading="loading">
      <el-checkbox v-for="item in list" :key="item.id" :label="item.id">{{ item.name }}</el-checkbox>
    </el-checkbox-group>
    <template #footer>
      <el-button type="primary" size="small" @click="clickSubmit">确定</el-button>
      <el-button size="small" @click="closeDialog">取消</el-button>
    </template>
  </el-dialog>
</template>

<script>
import { reqGetRoleList } from '@/api/setting'
import { reqGetUserDetailById } from '@/api/user'
import { reqAssignRoles } from '@/api/employees'
export default {
  name: 'AssignRole',
  props: {
    showRoleDialog: {
      type: Boolean,
      default: false
    },
    userId: {
      type: String,
      default: ''
    }
  },
  data() {
    return {
      roleIds: [],
      list: [],
      loading: false
    }
  },
  methods: {
    closeDialog() {
      this.$emit('update:showRoleDialog', false)
    },
    async openRoleDialog() {
    //   this.getRoleList()
    //   this.getUserDetailById()
      this.loading = true
      // 写法一
      // Promise.all([this.getRoleList(), this.getUserDetailById()]).then(() => { this.loading = false })
      // 写法二
      await Promise.all([this.getRoleList(), this.getUserDetailById()])
      this.loading = false
    },
    // 获取角色列表
    async getRoleList() {
      const { data } = await reqGetRoleList(1, 100)
      this.list = data.rows
    },
    // 获取员工角色
    async getUserDetailById() {
      const { data } = await reqGetUserDetailById(this.userId)
      //   console.log(data)
      this.roleIds = data.roleIds
    },
    // 给员工分配角色
    async clickSubmit() {
      await reqAssignRoles({
        id: this.userId,
        roleIds: this.roleIds
      })
      this.$message.success('分配角色成功')
      this.closeDialog()
    }
  }
}
</script>

<style>

</style>
